package com.hjp.model;

import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;


import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;

import org.hibernate.annotations.LazyCollection;
import org.hibernate.annotations.LazyCollectionOption;
import org.hibernate.annotations.LazyToOne;
import org.hibernate.annotations.LazyToOneOption;


/*
自关联的常见问题。
1.如果父节点删除了，则应该要把所有的子节点删除，要做到这一点，就需要在和子节点的关联时，设置cascade
2.删除子节点的时候因为他有外键关联到父节点，要想删除它必须先设置其父节点为null，然后update下，再来删除自己，
    当然由于它有向下的级联关系，所以它删除了，他的所有子节点也跟着删除了
3.另外，这里没有设置和父节点的级联，如果父节点是新建的，则要先保存父节点，再来保存自己


*/

@Entity
@Table(name = "t_department")
public class Department implements Serializable{
	private Long id;
	private String name;
	private String description;
	
	private Department parent;
	private Set<User> users = new HashSet<User>();
	private Set<Department> children = new HashSet<Department>();

	@Id
	@GeneratedValue
	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	@OneToMany(mappedBy="department")
	@LazyCollection(LazyCollectionOption.EXTRA)
	public Set<User> getUsers() {
		return users;
	}

	public void setUsers(Set<User> users) {
		this.users = users;
	}

	@ManyToOne(fetch=FetchType.EAGER)
//	@LazyToOne(LazyToOneOption.PROXY)
	@JoinColumn(name = "pid")
	public Department getParent() {
		return parent;
	}

	public void setParent(Department parent) {
		this.parent = parent;
	}

	//这里设置级联是为了在父节点删除的时候自动删除子节点，
	@OneToMany(fetch = FetchType.EAGER,cascade =CascadeType.ALL, mappedBy = "parent")
	
	public Set<Department> getChildren() {
		return children;
	}

	public void setChildren(Set<Department> children) {
		this.children = children;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getDescription() {
		return description;
	}

	public void setDescription(String description) {
		this.description = description;
	}

}
